Indexers in C# allow objects to be indexed like arrays. This is useful when your object represents a collection of values and you want to access its elements using the array-like
object[index] syntax.
What Is an Indexer?
An indexer lets you use the array index syntax ([]) on a class or struct to access data stored inside it — just like an array or a list.
It’s defined using the this keyword followed by an index parameter.
Syntax of an Indexer
class ClassName
{
private string[] data = new string[10];
public string this[int index]
{
get { return data[index]; }
set { data[index] = value; }
}
}
Example: Creating and Using an Indexer
using System;
class StudentNames
{
private string[] names = new string[5];
// Define the indexer
public string this[int index]
{
get { return names[index]; }
set { names[index] = value; }
}
}
class Program
{
static void Main()
{
StudentNames students = new StudentNames();
students[0] = "Alice";
students[1] = "Bob";
Console.WriteLine(students[0]); // Output: Alice
Console.WriteLine(students[1]); // Output: Bob
}
}
Key Points
- Indexers use the
thiskeyword. - You can define
getand/orsetaccessors. - You can overload indexers by changing the number or types of parameters.
- Indexers can be read-only, write-only, or read/write.
Indexers vs Properties
| Feature | Indexer | Property |
|---|---|---|
| Access | Via index (e.g., obj[0]) | By name (e.g., obj.Name) |
| Syntax | this[...] |
Property name |
| Use Case | Collection-like classes | Single values or settings |
Example: String-based Indexer
You can also create indexers that accept strings or other data types.
class BookLibrary
{
private Dictionary<string, string> books = new();
public string this[string title]
{
get { return books.ContainsKey(title) ? books[title] : "Not found"; }
set { books[title] = value; }
}
}
Usage
var library = new BookLibrary();
library["C#"] = "Learn C# in 21 Days";
Console.WriteLine(library["C#"]); // Output: Learn C# in 21 Days
Access Modifiers in Indexers
You can set different access modifiers for the get and set parts:
public string this[int index]
{
get { return data[index]; }
private set { data[index] = value; }
}
Summary
| Concept | Description |
|---|---|
| What is it? | Allows class objects to be indexed like arrays |
| Defined by | Using this[index] with get/set |
| Return Type | Can be any type |
| Parameters | Can take any number and type |
| Use Case | Useful for custom collections and wrappers |
Read More -
Leave Comment